/*
 * // Bristleback plugin - Copyright (c) 2010 bristleback.googlecode.com
 * // ---------------------------------------------------------------------------
 * // This program is free software; you can redistribute it and/or modify it
 * // under the terms of the GNU Lesser General Public License as published by the
 * // Free Software Foundation; either version 3 of the License, or (at your
 * // option) any later version.
 * // This library is distributed in the hope that it will be useful,
 * // but without any warranty; without even the implied warranty of merchantability
 * // or fitness for a particular purpose.
 * // You should have received a copy of the GNU Lesser General Public License along
 * // with this program; if not, see <http://www.gnu.org/licenses/lgpl.html>.
 * // ---------------------------------------------------------------------------
 */

package pl.bristleback.server.bristle.binding;

import org.apache.log4j.Logger;

/**
 * Utility class that has methods for resolving binding errors.
 * <p/>
 * Created on: 2011-03-13 09:31:47 <br/>
 *
 * @author Wojciech Niemiec
 */
public class BindingErrorsResolver {
  private static Logger log = Logger.getLogger(BindingErrorsResolver.class.getName());

  /**
   * Checks whether given field or its children are required and adds a not null violation error for each required field found.
   *
   * @param bindingResult    binding result wrapper.
   * @param fieldInformation information about checked field.
   */
  public void checkAndAddNotNullViolationErrors(BindingResult<?> bindingResult, NestedFieldInformation fieldInformation) {
    if (!fieldInformation.isRequired()) {
      return;
    }
    if (!fieldInformation.isIntermediary()) {
      BindingError notNullError = BindingError.addNotNullViolationError(fieldInformation.getFullPathName());
      bindingResult.getErrors().add(notNullError);
    } else {
      if (fieldInformation.isContainer()) {
        addNotNullViolationErrorsInChildren(fieldInformation.getElementFieldInformation(), bindingResult);
      } else {
        addNotNullViolationErrorsInChildren(fieldInformation, bindingResult);
      }
    }
  }

  private void addNotNullViolationErrorsInChildren(NestedFieldInformation fieldInformation, BindingResult<?> bindingResult) {
    for (NestedFieldInformation child : fieldInformation.getChildrenList()) {
      checkAndAddNotNullViolationErrors(bindingResult, child);
    }
  }
}
